using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Permissions;
using System.Windows.Forms;

namespace Common.Shared.Windows.Forms {
  public class FolderFileSystemTreeNode : FileSystemTreeNode {
    SystemImageList _imageList = null;
    public FolderFileSystemTreeNode ( DirectoryInfo directory ) : base() {
      this.directoryInfo = directory;
      this.Text = directoryInfo.Name;
      new FileIOPermission ( FileIOPermissionAccess.PathDiscovery, this.directoryInfo.FullName ).Demand ( );
      if ( HasFoldersOrFiles )
        this.Nodes.Add ( new DummyTreeNode ( ) );
    }

    public override void SetIcons ( SystemImageList imageList ) {
      if ( imageList != null ) {
        _imageList = imageList;
        ShellIconStateConstants state = this.IsExpanded ? 
          ShellIconStateConstants.ShellIconStateOpen : ShellIconStateConstants.ShellIconStateNormal;
        this.ImageIndex = this.SelectedImageIndex = imageList.IconIndex ( this.directoryInfo.FullName, true, state );
      }
    }

    internal override void OnAfterCollapse ( TreeViewEventArgs e ) {
      base.OnAfterCollapse ( e );
      this.SetIcons ( this._imageList );
    }

    internal override void OnAfterExpand ( TreeViewEventArgs e ) {
      base.OnAfterExpand ( e );
      this.SetIcons ( this._imageList );
    }

    public bool HasFoldersOrFiles {
      get {
        //return this.directoryInfo.GetDirectories ( ).Length > 0 || this.directoryInfo.GetFiles ( ).Length > 0;
        new FileIOPermission ( FileIOPermissionAccess.PathDiscovery, this.directoryInfo.FullName ).Demand ( );
        try {
          foreach ( DirectoryInfo dir in this.DirectoryInfo.GetDirectories ( ) ) {
            try {
              return true;
            } catch {
              continue;
            }
          }

          foreach ( FileInfo file in this.DirectoryInfo.GetFiles ( ) ) {
            try {
              return true;
            } catch {
              continue;
            }
          }
        } catch { }
        return false;
      }
    }
  }
}
